import 'dart:async';

import 'package:enjoy_plus_test/utils/http.dart';
import 'package:enjoy_plus_test/utils/toast.dart';
import 'package:flutter/material.dart';

import '../../utils/eventbus.dart';
import '../../utils/token.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // TextEditingController文本编辑控制器，用于控制 TextField 或 TextFormField 的输入内容
  // 能够读取或修改输入框的文本 (_phoneController.text)、监听文本变化（通过 addListener）
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  void _submit() async{
    // 3.1 校验手机号
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号码');
    }
    if (! RegExp(r'^1[3-9]\d{9}$').hasMatch(_phoneController.text)) {
      return ToastUtil.showError('请输入正确的手机号码');
    }

    // 3.2 校验验证码
    if (_codeController.text.isEmpty) {
      return ToastUtil.showError('请输入验证码');
    }
    if (! RegExp(r'^\d{6}$').hasMatch(_codeController.text)) {
      return ToastUtil.showError('请输入6位验证码');
    }
    // 3.3 调用登录接口
    final res = await http.post('/login', data: {
      'mobile': _phoneController.text,
      'code': _codeController.text,
    });
    if (res['code'] != 10000) return ToastUtil.showError('登录失败');

    // 3.4 存储token
    TokenManager().saveToken(res['data']['token']);
    ToastUtil.showSuccess('登录成功');
    // 重新获取个人中心数据
    eventBus.fire(RefreshMine());
    _timer?.cancel();
    Navigator.pop(context);
  }

  int _countdown = 60; //倒计时的秒数
  bool _isCountDown = false; //是否正在倒计时
  Timer? _timer;
  void _getVerificarionCode() async{
    if(_phoneController.text.isEmpty){
      return ToastUtil.showError('请输入手机号');
    }
    // 在正则表达式前的 r 表示这是一个原始字符串（Raw String），它的作用是让字符串中的反斜杠 \ 保持原义，避免被转义
    RegExp regExp=RegExp(r'^1[3-9]\d{9}$');
    if(!regExp.hasMatch(_phoneController.text)){
      return ToastUtil.showError('请输入正确的手机号！');
    }

    var res=await http.get('/code',params: {
      'mobile':_phoneController.text,
    });
    if(res['code']!=10000)return ToastUtil.showError('获取验证码失败');
    ToastUtil.showSuccess('验证码已发送!');
    Future.delayed(const Duration(seconds: 2),(){
      _codeController.text=res['data']['code'];
    });
    _startCountdown();
  }

  void _startCountdown() {
    if (_isCountDown) {
      //   如果已经在倒计时，
      return;
    }
    _isCountDown = true;
    // 创建每秒触发一次的周期性 Timer
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 0) {
          _countdown--;
        } else {
          _isCountDown = false;
          _countdown = 60;
          timer.cancel();
        }
      });
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer?.cancel();
    _phoneController.dispose();
    _codeController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                ),
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                 Expanded(
                  child: TextField(
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    maxLength: 11,
                    decoration: InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    // _startCountdown();
                    _getVerificarionCode();

                  },
                  child:
                      _isCountDown
                          ? Text(
                            '$_countdown s后重新获取',
                            style: const TextStyle(color: Colors.grey),
                          )
                          : const Text('获取验证码'),
                ),
              ],
            ),
            const SizedBox(height: 8),
             TextField(
              controller: _codeController,
              keyboardType: TextInputType.number,
              maxLength: 6,
              decoration: InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _submit();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
